package com.atguigu.gulimall.ware.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import com.atguigu.common.exception.BizErrorCode;
import com.atguigu.common.to.ware.HasSkuStockTo;
import com.atguigu.common.to.ware.WareSkuLockRequestTo;
import com.atguigu.common.exception.ware.NoEnoughStockException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.atguigu.gulimall.ware.entity.WareSkuEntity;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.R;


/**
 * 商品库存
 *
 * @author zhough
 * @email zhough@gmail.com
 * @date 2024-01-22 20:28:15
 */
@RestController
@RequestMapping("ware/waresku")
public class WareSkuController {
    @Autowired
    private WareSkuService wareSkuService;

    /**
     * 锁定订单库存
     *
     * @param to 订单锁定信息
     * @return R
     */
    @PostMapping("/stock/lock")
    public R lockSkuItem(@RequestBody WareSkuLockRequestTo to) {

        try {
            wareSkuService.lockSkuItem(to);
            return R.ok();
        } catch (NoEnoughStockException exception) {
            return R.error(BizErrorCode.NO_ENOUGH_STOCK_ERROR);
        }
    }

    /**
     * 列表
     */
    @RequestMapping("/hasstock")
    // @RequiresPermissions("ware:waresku:list")
    public R hasSkuStock(@RequestBody List<Long> skuIds) {
        List<HasSkuStockTo> data = wareSkuService.hasSkuStock(skuIds);

        R ok = R.ok();
        ok.setData(data);
        return ok;
//        return R.ok().put("data",data);
    }

    /**
     * 列表
     */
    @RequestMapping("/list")
    // @RequiresPermissions("ware:waresku:list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = wareSkuService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    // @RequiresPermissions("ware:waresku:info")
    public R info(@PathVariable("id") Long id) {
        WareSkuEntity wareSku = wareSkuService.getById(id);

        return R.ok().put("wareSku", wareSku);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    // @RequiresPermissions("ware:waresku:save")
    public R save(@RequestBody WareSkuEntity wareSku) {
        wareSkuService.save(wareSku);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    // @RequiresPermissions("ware:waresku:update")
    public R update(@RequestBody WareSkuEntity wareSku) {
        wareSkuService.updateById(wareSku);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    // @RequiresPermissions("ware:waresku:delete")
    public R delete(@RequestBody Long[] ids) {
        wareSkuService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

}
